import java.util.ArrayList;
import java.util.List;

public class Find {
    public static void main(String[] args) {
        int max = 20000;
        List<Integer> primes = findPrimes(max);
        System.out.println("1~" + max + "之间的素数共有 " + primes.size() + " 个");

        printPrimes(primes, 5);
    }

    public static List<Integer> findPrimes(int max) {
        if (max < 2) {
            return new ArrayList<>();
        }

        boolean[] isPrime = new boolean[max + 1];
        for (int i = 2; i <= max; i++) {
            isPrime[i] = true;
        }

        for (int p = 2; p * p <= max; p++) {
            if (isPrime[p]) {
                for (int i = p * p; i <= max; i += p) {
                    isPrime[i] = false;
                }
            }
        }

        List<Integer> primes = new ArrayList<>();
        for (int i = 2; i <= max; i++) {
            if (isPrime[i]) {
                primes.add(i);
            }
        }

        return primes;
    }

    public static void printPrimes(List<Integer> primes, int numbersPerLine) {
        for (int i = 0; i < primes.size(); i++) {
            System.out.printf("%6d", primes.get(i));
            if ((i + 1) % numbersPerLine == 0) {
                System.out.println();
            }
        }
    }
}

